#pragma once

#include <windef.h>
#include <winuser.h>

#include <ctime>
#include <iostream>
#include <string>

#include "MouseShaker.h"

HWND h_editMoveDis;
HWND h_editTimeInterval;
HWND h_textStatus;
HWND h_textLoopTimes;
std::time_t h_lastMovedTime;
bool h_timerStarted = false;
int h_loopTimes;
int h_moveDis;
int h_timeInterval;


void UpdateStatusText()
{
    std::wstring statusText = h_timerStarted ? L"Status: Running" : L"Status: Stopped";
    SetWindowText(h_textStatus, statusText.c_str());
}

void UpdateLoopTimesText()
{
    std::wstring text = L"LoopTimes: " + std::to_wstring(h_loopTimes);
    SetWindowText(h_textLoopTimes, text.c_str());
}

void CreateMouseEvent()
{
    int dis = h_loopTimes % 2 == 0 ? h_moveDis : -h_moveDis;
    mouse_event(MOUSEEVENTF_MOVE, dis, dis, 0, NULL);
}

void StartShake(HWND hWnd)
{
    wchar_t editStr1[1024] = L"";
    GetWindowText(h_editMoveDis, editStr1, 1024);
    h_moveDis = _wtoi(editStr1);
    wchar_t editStr2[1024] = L"";
    GetWindowText(h_editTimeInterval, editStr2, 1024);
    h_timeInterval = _wtoi(editStr2);

    SetTimer(hWnd, IDT_TIMER_ID, h_timeInterval * 1000, NULL);
    h_lastMovedTime = std::time(0);
    h_timerStarted = true;

    UpdateLoopTimesText();
    UpdateStatusText();
}

void StopShake(HWND hWnd)
{
    KillTimer(hWnd, IDT_TIMER_ID);
    h_timerStarted = false;
    h_loopTimes = 0;
    h_lastMovedTime = std::time(0);

    UpdateLoopTimesText();
    UpdateStatusText();
}

void NotifyMouseMove(int x, int y)
{
    h_lastMovedTime = std::time(0);
}

void TimerShake()
{
    h_loopTimes++;

    std::time_t interval = std::time(0) - h_lastMovedTime;

    if (interval >= h_timeInterval)
        CreateMouseEvent();
    else
        std::cout << "TimerShake interval less than timeInterval";

    UpdateLoopTimesText();
}
